/**
 * @description 圈子 router
 */
const router = require('koa-router')()
const koaForm = require('formidable-upload-koa')
const loginCheck = require('../middlewares/loginCheck')
const { saveOpinion, getOpinionList } = require('../controller/circles')
const { saveFile } = require('../controller/shared')

router.prefix('/api/circles')

/**
 * 文件上传 - 上传圈子图片
 * @param {binary} file 文件对象
 */
router.post('/uploadImg', loginCheck, koaForm(), async (ctx, next) => {
  // 获取前端传来的文件，其中 file 字段取决于前端传参
  const file = ctx.req.files['file']
  const { type, name, path, size } = file
  ctx.body = await saveFile({ type, name, filePath: path, size }, 'circlesImg')
})

/**
 * 发布圈子动态
 * @param {number} releaseProvinceId 省份 ID
 * @param {number} releaseCityId 城市 ID
 * @param {string} content 动态内容
 * @param {array} imgUrls 圈子图片地址数组
 */
router.post(
  '/opinion',
  loginCheck,
  async (ctx, next) => {
    const { releaseProvinceId, releaseCityId, content, imgUrls } = ctx.request.body
    ctx.body = await saveOpinion(ctx, { releaseProvinceId, releaseCityId, content, imgUrls })
  }
)

/**
 * 获取近 20 条动态列表
 */
router.get(
  '/opinionList',
  loginCheck,
  async (ctx, next) => {
    ctx.body = await getOpinionList()
  }
)

module.exports = router
